import { useEffect, useState } from 'react';
import {
  GlobeAltIcon,
  DocumentTextIcon,
  ChartBarIcon,
  ClockIcon,
  PlayIcon,
  StopIcon,
  ArrowDownTrayIcon,
} from '@heroicons/react/24/outline';
import { Button } from '@components/ui';
import {
  useTauriCommand,
  useNotifications,
  useWindowState,
} from '@hooks/useTauri';
import { useConfig } from '@stores/appStore';
import { cn } from '@utils/index';
import toast from 'react-hot-toast';

const Home: React.FC = () => {
  const [, setAppInfo] = useState<any>(null);
  const [crawlerStats] = useState({
    totalTasks: 0,
    activeTasks: 0,
    completedTasks: 0,
    totalPages: 0,
    successRate: 0,
  });
  const config = useConfig();
  const { sendNotification } = useNotifications();
  const { center } = useWindowState();

  const { invoke: getAppInfo } = useTauriCommand('get_app_info');
  const { invoke: startCrawler, loading: startingCrawler } =
    useTauriCommand('start_crawler');
  const { invoke: stopCrawler, loading: stoppingCrawler } =
    useTauriCommand('stop_crawler');

  useEffect(() => {
    // Load app information on component mount
    loadAppInfo();
  }, []);

  const loadAppInfo = async () => {
    try {
      const info = await getAppInfo();
      setAppInfo(info);
    } catch (error) {
      console.error('Failed to load app info:', error);
    }
  };

  const handleStartCrawler = async () => {
    try {
      await startCrawler({ url: 'https://example.com' });
      toast.success('Crawler started successfully');
      await sendNotification({
        title: 'Crawler Started',
        body: 'Web crawler has been started successfully!',
      });
    } catch (error) {
      toast.error('Failed to start crawler');
    }
  };

  const handleStopCrawler = async () => {
    try {
      await stopCrawler();
      toast.success('Crawler stopped');
    } catch (error) {
      toast.error('Failed to stop crawler');
    }
  };

  const features = [
    {
      icon: GlobeAltIcon,
      title: 'Multi-Platform Crawling',
      description:
        'Crawl websites across different platforms with intelligent handling.',
      color: 'text-blue-500',
    },
    {
      icon: DocumentTextIcon,
      title: 'Smart Data Extraction',
      description:
        'Extract structured data using CSS selectors, XPath, and regex.',
      color: 'text-green-500',
    },
    {
      icon: ChartBarIcon,
      title: 'Real-time Analytics',
      description: 'Monitor crawling progress and performance in real-time.',
      color: 'text-purple-500',
    },
    {
      icon: ClockIcon,
      title: 'Scheduled Tasks',
      description: 'Set up automated crawling tasks with flexible scheduling.',
      color: 'text-red-500',
    },
    {
      icon: ArrowDownTrayIcon,
      title: 'Multiple Export Formats',
      description: 'Export data to JSON, CSV, Excel, XML and more formats.',
      color: 'text-yellow-500',
    },
    {
      icon: PlayIcon,
      title: 'Easy to Use',
      description: 'Intuitive interface with powerful crawling capabilities.',
      color: 'text-indigo-500',
    },
  ];

  return (
    <div className="mx-auto max-w-6xl">
      {/* Hero Section */}
      <div className="mb-12 text-center">
        <div className="mb-6">
          <div className="mb-4 inline-flex h-20 w-20 items-center justify-center rounded-full bg-primary-100 dark:bg-primary-900">
            <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary-500">
              <div className="h-6 w-6 rounded-sm bg-white"></div>
            </div>
          </div>
        </div>

        <h1 className="mb-4 text-4xl font-bold text-gray-900 dark:text-gray-100">
          Multi-Platform Web Crawler
        </h1>

        <p className="mx-auto mb-8 max-w-3xl text-xl text-gray-600 dark:text-gray-400">
          A powerful and efficient web crawler built with Tauri, React,
          TypeScript, and Rust. Extract data from websites with intelligent
          parsing, export to multiple formats, and manage crawling tasks with
          ease.
        </p>

        <div className="flex flex-wrap justify-center gap-4">
          <Button onClick={handleStartCrawler} loading={startingCrawler}>
            <PlayIcon className="mr-2 h-4 w-4" />
            Start Crawler
          </Button>
          <Button
            variant="outline"
            onClick={handleStopCrawler}
            loading={stoppingCrawler}
          >
            <StopIcon className="mr-2 h-4 w-4" />
            Stop Crawler
          </Button>
          <Button variant="ghost" onClick={center}>
            Center Window
          </Button>
        </div>
      </div>

      {/* Crawler Statistics */}
      <div className="mb-8 grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-5">
        <div className="rounded-lg border border-gray-200 bg-white p-6 shadow-sm dark:border-gray-700 dark:bg-gray-800">
          <div className="flex items-center">
            <div className="flex-shrink-0">
              <ChartBarIcon className="h-8 w-8 text-blue-500" />
            </div>
            <div className="ml-4">
              <p className="text-sm font-medium text-gray-500 dark:text-gray-400">
                Total Tasks
              </p>
              <p className="text-2xl font-semibold text-gray-900 dark:text-gray-100">
                {crawlerStats.totalTasks}
              </p>
            </div>
          </div>
        </div>

        <div className="rounded-lg border border-gray-200 bg-white p-6 shadow-sm dark:border-gray-700 dark:bg-gray-800">
          <div className="flex items-center">
            <div className="flex-shrink-0">
              <PlayIcon className="h-8 w-8 text-green-500" />
            </div>
            <div className="ml-4">
              <p className="text-sm font-medium text-gray-500 dark:text-gray-400">
                Active Tasks
              </p>
              <p className="text-2xl font-semibold text-gray-900 dark:text-gray-100">
                {crawlerStats.activeTasks}
              </p>
            </div>
          </div>
        </div>

        <div className="rounded-lg border border-gray-200 bg-white p-6 shadow-sm dark:border-gray-700 dark:bg-gray-800">
          <div className="flex items-center">
            <div className="flex-shrink-0">
              <DocumentTextIcon className="h-8 w-8 text-purple-500" />
            </div>
            <div className="ml-4">
              <p className="text-sm font-medium text-gray-500 dark:text-gray-400">
                Completed
              </p>
              <p className="text-2xl font-semibold text-gray-900 dark:text-gray-100">
                {crawlerStats.completedTasks}
              </p>
            </div>
          </div>
        </div>

        <div className="rounded-lg border border-gray-200 bg-white p-6 shadow-sm dark:border-gray-700 dark:bg-gray-800">
          <div className="flex items-center">
            <div className="flex-shrink-0">
              <GlobeAltIcon className="h-8 w-8 text-yellow-500" />
            </div>
            <div className="ml-4">
              <p className="text-sm font-medium text-gray-500 dark:text-gray-400">
                Pages Crawled
              </p>
              <p className="text-2xl font-semibold text-gray-900 dark:text-gray-100">
                {crawlerStats.totalPages}
              </p>
            </div>
          </div>
        </div>

        <div className="rounded-lg border border-gray-200 bg-white p-6 shadow-sm dark:border-gray-700 dark:bg-gray-800">
          <div className="flex items-center">
            <div className="flex-shrink-0">
              <ChartBarIcon className="h-8 w-8 text-red-500" />
            </div>
            <div className="ml-4">
              <p className="text-sm font-medium text-gray-500 dark:text-gray-400">
                Success Rate
              </p>
              <p className="text-2xl font-semibold text-gray-900 dark:text-gray-100">
                {crawlerStats.successRate}%
              </p>
            </div>
          </div>
        </div>
      </div>

      {/* Features Grid */}
      <div className="mb-12">
        <h2 className="mb-8 text-center text-2xl font-bold text-gray-900 dark:text-gray-100">
          Crawler Features & Capabilities
        </h2>

        <div className="grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3">
          {features.map((feature, index) => (
            <div
              key={index}
              className={cn(
                'rounded-lg border border-gray-200 bg-white shadow-sm dark:border-gray-700 dark:bg-gray-800',
                'p-6 transition-shadow hover:shadow-md'
              )}
            >
              <div className="mb-4 flex items-center">
                <feature.icon className={cn('h-8 w-8', feature.color)} />
                <h3 className="ml-3 text-lg font-semibold text-gray-900 dark:text-gray-100">
                  {feature.title}
                </h3>
              </div>
              <p className="text-gray-600 dark:text-gray-400">
                {feature.description}
              </p>
            </div>
          ))}
        </div>
      </div>

      {/* Configuration Section */}
      <div className="rounded-lg border border-gray-200 bg-white p-6 shadow-sm dark:border-gray-700 dark:bg-gray-800">
        <h2 className="mb-4 text-lg font-semibold text-gray-900 dark:text-gray-100">
          Current Configuration
        </h2>

        <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
          <div>
            <h3 className="mb-2 text-sm font-medium text-gray-500 dark:text-gray-400">
              Theme Settings
            </h3>
            <div className="space-y-2">
              <div className="flex justify-between">
                <span className="text-sm text-gray-700 dark:text-gray-300">
                  Theme:
                </span>
                <span className="text-sm font-medium capitalize text-gray-900 dark:text-gray-100">
                  {config.theme}
                </span>
              </div>
              <div className="flex justify-between">
                <span className="text-sm text-gray-700 dark:text-gray-300">
                  Language:
                </span>
                <span className="text-sm font-medium text-gray-900 dark:text-gray-100">
                  {config.language}
                </span>
              </div>
            </div>
          </div>

          <div>
            <h3 className="mb-2 text-sm font-medium text-gray-500 dark:text-gray-400">
              App Settings
            </h3>
            <div className="space-y-2">
              <div className="flex justify-between">
                <span className="text-sm text-gray-700 dark:text-gray-300">
                  Auto Start:
                </span>
                <span
                  className={cn(
                    'text-sm font-medium',
                    config.autoStart
                      ? 'text-green-600 dark:text-green-400'
                      : 'text-gray-500'
                  )}
                >
                  {config.autoStart ? 'Enabled' : 'Disabled'}
                </span>
              </div>
              <div className="flex justify-between">
                <span className="text-sm text-gray-700 dark:text-gray-300">
                  Notifications:
                </span>
                <span
                  className={cn(
                    'text-sm font-medium',
                    config.notifications
                      ? 'text-green-600 dark:text-green-400'
                      : 'text-gray-500'
                  )}
                >
                  {config.notifications ? 'Enabled' : 'Disabled'}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Home;
